<template>
    <div class="content">
        <Form :label-width="140" :model="form" ref="form" :rules="rules">
            <FormItem label="用户名" prop="userName">
                <Input
                    v-model="form.userName"
                    :disabled="!!form.userId"
                    placeholder="3~10位不可重复"
                ></Input>
            </FormItem>
            <FormItem label="登录密码" prop="userPwd">
                <Input
                    :disabled="!!form.userId"
                    type="password"
                    v-model="pwd"
                    placeholder="请输入登录密码"
                    autocomplete="new-password"
                ></Input>
            </FormItem>
            <FormItem label="姓名" prop="realName">
                <Input
                    v-model="form.realName"
                    placeholder="请输入姓名"
                ></Input>
            </FormItem>
            <FormItem label="所属院校" prop="schoolId">
                <RemoteSearch
                    v-model="form.schoolId"
                    :list="schoolList"
                    keywordFiled="label"
                    valueField="value"
                    :labelFieldList="['label']"
                />
            </FormItem>
            <FormItem label="联系方式" prop="contacts">
                <Input
                    v-model="form.contacts"
                    placeholder="请输入联系方式"
                    :maxlength="12"
                ></Input>
            </FormItem>
            <FormItem label="状态" prop="status">
                <Select
                    style="width: 100%;"
                    placeholder="状态"
                    v-model="form.status"
                    clearable
                >
                    <Option :value="1">有效</Option>
                    <Option :value="0">失效</Option>
                </Select>
            </FormItem>
            <FormItem label="备注" prop="remark">
                <Input v-model="form.remark" type="textarea"></Input>
            </FormItem>
            <FormItem>
                <div class="submit-footer">
                    <Button type="primary" @click="submit">保存</Button>
                    <Button @click="handleCancel">取消</Button>
                </div>
            </FormItem>
        </Form>
    </div>
</template>
<script>
import { mapMutations } from 'vuex'
import { addUser, updateUser, queryUserInfo } from '@/api/userManage'
import { schoolManageList } from '@/api/schoolManage'

export default {
    inject: ['nextPageReload'],
    data () {
        const validateStatus = (rule, value, callback) => {
            if (typeof value !== 'number') {
                callback(new Error('状态必选'))
            } else {
                callback()
            }
        }
        return {
            schoolList: [],
            form: {
                roleType: 2,
                contacts: '',
                status: 1,
                realName: '',
                remark: '',
                schoolId: '',
                userId: '',
                userName: '',
                userPwd: ''
            },
            rules: {
                userName: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '用户名必填'
                    },
                    {
                        min: 3,
                        max: 10,
                        trigger: 'blur',
                        message: '用户名3-10位'
                    }
                ],
                userPwd: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (this.form.userId || value) {
                                /^.{3,10}$/.test(value) ? callback() : callback(new Error('密码3-10位, 字母数字任意组合'))
                            } else {
                                callback(new Error('登录密码必填'))
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                realName: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '姓名必填'
                    },
                    {
                        min: 2,
                        max: 10,
                        trigger: 'blur',
                        message: '姓名2-10位'
                    }
                ],
                schoolId: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '所属院校必填'
                    }
                ],
                status: [
                    {
                        required: true,
                        validator: validateStatus,
                        trigger: 'change'
                    }
                ]
            }
        }
    },
    computed: {
        pwd: {
            get () {
                return this.form.userId ? '********' : this.form.userPwd
            },
            set (v) {
                if (this.form.userId) return
                this.form.userPwd = v
            }
        }
    },
    mounted () {
        const id = this.$route.params.id
        if (id) {
            this.queryInfo(id)
        }
        this.querySchool()
    },
    methods: {
        ...mapMutations(['removeTagNav']),
        submit () {
            this.$refs.form.validate(v => {
                if (v) {
                    const enable = this.form.status === 1
                    const fn = this.form.userId ? updateUser : addUser
                    fn({
                        ...this.form,
                        enable
                    }).then(res => {
                        if (res.data.code === '0000') {
                            this.$Message.success(`保存成功`)
                            this.nextPageReload()
                            this.handleCancel()
                        } else {
                            this.$Message.error(res.data.data || res.data.msg)
                        }
                    })
                }
            })
        },
        handleCancel () {
            this.removeTagNav(this.$route)
            this.$router.replace({
                name: 'userManageList'
            })
        },
        setFormByUserInfo (data) {
            if (!data) return
            Object.keys(this.form).forEach(k => {
                if (data.hasOwnProperty(k)) {
                    this.form[k] = data[k]
                }
            })
            if (typeof data.enable === 'boolean') {
                this.form.status = data.enable ? 1 : 0
            } else {
                this.form.status = ''
            }
        },
        queryInfo (id) {
            queryUserInfo(id).then(res => {
                if (res.data.code === '0000') {
                    this.setFormByUserInfo(res.data.data)
                }
            })
        },
        querySchool () {
            return schoolManageList({
                pageNum: 1,
                pageSize: 10000,
                schoolName: ''
            }).then(res => {
                if (res.data.code === '0000') {
                    const schoolList = res.data.data.list.map(item => {
                        return {
                            value: item.schoolId,
                            label: item.schoolName
                        }
                    })
                    this.schoolList = Object.freeze(schoolList)
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
.ivu-form {
    max-width: 800px;
}
</style>
